identity = -> new Float32Array [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]

mult = (a, b) ->
  d = new Float32Array 9

  d[0] = a[0] * b[0] + a[1] * b[3]  + a[2] * b[6]
  d[1] = a[0] * b[1] + a[1] * b[4]  + a[2] * b[7]
  d[2] = a[0] * b[2] + a[1] * b[5]  + a[2] * b[8]

  d[3] = a[3] * b[0] + a[4] * b[3]  + a[5] * b[6]
  d[4] = a[3] * b[1] + a[4] * b[4]  + a[5] * b[7]
  d[5] = a[3] * b[2] + a[4] * b[5]  + a[5] * b[8]

  d[6] = a[6] * b[0] + a[7] * b[3]  + a[8] * b[6]
  d[7] = a[6] * b[1] + a[7] * b[4]  + a[8] * b[7]
  d[8] = a[6] * b[2] + a[7] * b[5]  + a[8] * b[8]

  return d


class window.Transform2D
  constructor : () ->
    @t = identity()
    @r = identity()
    @s = identity()

    @rotation = 0.0

  setTranslation : (x, y) ->
    @t[2] = x
    @t[5] = y

  translate : (x, y) ->
    @t[2] += x
    @t[5] += y

  setRotation : (d) ->
    @rotation = d
    cos = Math.cos @rotation
    sin = Math.sin @rotation

    @r[0] = @r[4] = cos
    @r[1] = -sin
    @r[3] = sin
  
  rotate : (d) ->
    @rotation = d + @rotation
    cos = Math.cos @rotation
    sin = Math.sin @rotation    

    @r[0] = @r[4] = cos
    @r[1] = -sin
    @r[3] = sin



  setScale : (sx, sy) ->
    sy ?= sx
    @s[0] = sx
    @s[4] = sy


  scale : (sx, sy) ->
    sy ?= sx
    @s[0] *= sx
    @s[4] *= sy

  getMatrix : () ->
    mult @t, @s
    